const app = getApp();
var revenueApi = require('../../script/revenue.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navHeight: app.globalData.statusBarHeight,
    h: 120,
    opacity: 0,
    scrollThreshold: 60,
    top: 0,
    date: '',
    day: '',
    value: 25,
    gradientColor: {
      '0%': '#31E749',
      '100%': '#28B93D',
    },
    CurrentPage: 1,
    PageSize: 20,
    HasNextPage: true,
    dataList: [],
    TotalCount: 0,
    FinishedCount: 0,
    PlannedCount: 0,
    CompleteRate: 0,
    noData: false,
    isReachBottom: false,
    curOrder: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // wx.setNavigationBarColor({
    //   frontColor: '#000000',
    //   backgroundColor: '#ffffff',
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getDate();
    this.getTaskCount();
    this.getOrderList(true);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    this._refreshData();
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.setData({
      isReachBottom: true
    });
    if (this.data.HasNextPage) {
      this.setData({
        CurrentPage: this.data.CurrentPage + 1
      })
      this.getOrderList();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onPageScroll(e) {
    const scrollTop = e.scrollTop;
    let opacity = 1;
    let top = 0;
    let h = 0;
    // 计算透明度，随着scrollTop增大从1变0
    if (scrollTop >= this.data.scrollThreshold) {
      opacity = 1;
      top = 120;
      h = 60;
    } else if (scrollTop < this.data.scrollThreshold) {
      opacity = scrollTop / this.data.scrollThreshold;
      h = 120 - scrollTop;
      top = 120 * scrollTop / this.data.scrollThreshold;
    } else {
      opacity = 0;
      h = 120;
      top = 0;
    }
    this.setData({
      opacity,
      h,
      top
    });
  },
  _refreshData() {
    this.setData({
      CurrentPage: 1,
      HasNextPage: true,
      HasNextPage: true,
      dataList: [],
      noData: false,
      isReachBottom: false,
    });
    this.getTaskCount();
    this.getOrderList(true);
  },
  getDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const date = now.getDate().toString().padStart(2, '0');
    const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][now.getDay()];
    this.setData({
      date: year + '/' + month + '/' + date,
      day: week
    });
  },
  back() {
    wx.navigateBack();
  },
  getTaskCount() {
    const params = {
      Data: JSON.stringify({
        Date: this.data.date,
      }),
    }
    revenueApi.QueryTaskCount(params).then(res => {
      if (res.code === 200) {
        let rate = 0;
        if (res.data.TotalCount > 0) {
          rate = Math.round(res.data.FinishedCount * 100 / res.data.TotalCount) / 100
        }
        this.setData({
          TotalCount: res.data.TotalCount,
          FinishedCount: res.data.FinishedCount,
          PlannedCount: res.data.PlannedCount,
          CompleteRate: rate
        });
      }
    })
  },
  getOrderList(isRefresh) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const params = {
      Data: JSON.stringify({
        AUDIT_TYPE: 0,
        CurrentPage: this.data.CurrentPage,
        PageSize: this.data.PageSize,
        DEPT_PART: '',
        ROOM: '',
        SelectedDate: this.data.date,
        UserCode: '',
        UserName: ''
      }),
    }
    revenueApi.QueryCheckPlanList(params).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        let dataList = []
        if (isRefresh) {
          dataList = [...res.data.DataList]
        } else {
          dataList = [...this.data.dataList, ...res.data.DataList]
        }
        let HasNextPage = res.data.HasNextPage;
        const noData = dataList.length === 0
        this.setData({
          dataList,
          HasNextPage,
          noData
        })
      }
    }).catch(_err => {
      wx.hideLoading();
    });
  },
  Call: function (e) {
    var pnonenum = e.currentTarget.dataset.phone;
    if (pnonenum == null || pnonenum == '') {
      wx.showToast({
        title: '暂无电话号码',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    var res = wx.getSystemInfoSync();
    if (res.platform == 'ios') {
      wx.makePhoneCall({
        phoneNumber: pnonenum
      });
    } else {
      wx.showActionSheet({
        itemList: [pnonenum, '呼叫'],
        success: function (res) {
          if (res.tapIndex == 1) {
            wx.makePhoneCall({
              phoneNumber: pnonenum
            })
          }
        }
      })
    }
  },
  toMap(e) {
    var order = e.currentTarget.dataset.order;
    if (order.Lat == null || order.Lat == 0 || order.Lng == null || order.Lng == 0) {
      wx.showModal({
        title: '位置上报',
        content: '当前用户无位置信息，是否立即上报？',
        success: (res) => {
          if (res.confirm) {
            wx.chooseLocation({
              success: (res) => {
                const params = {
                  Data: JSON.stringify({
                    UserCode: order.UserCode,
                    Lat: res.data.latitude,
                    Lng: res.data.longitude,
                  })
                }
                revenueApi.UpdateConsPosition(params).then(res => {
                  if (res.code === 200) {
                    wx.showToast({
                      title: '上报成功！',
                      icon: 'none',
                      duration: 1500
                    });
                    this._refreshData();
                  }
                })
              }
            });
          }
        }
      })
    } else {
      wx.openLocation({
        latitude: order.Lat,
        longitude: order.Lng,
        address: info.WATER_ADDR,
        scale: 18
      })
      // wx.getLocation({
      //   type: 'gcj02', //返回可以用于 wx.openLocation 的经纬度
      //   success(res) {
      //     const latitude = res.latitude
      //     const longitude = res.longitude
      //     wx.openLocation({
      //       latitude,
      //       longitude,
      //       address: info.Address,
      //       scale: 18
      //     })
      //   }
      // })
    }
  },
  CancelPlan(e) {
    var id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '请确认是否取消计划？',
      content: '提示：取消计划后，可针对本户重新计划',
      success: (res) => {
        if (res.confirm) {
          const params = {
            Data: JSON.stringify({
              TaskDetailNos: id,
              PlanDate: '', // 当时间为空时，代表取消计划
            })
          }
          revenueApi.UpdateTaskPlan(params).then(res => {
            if (res.code === 200) {
              wx.showToast({
                title: '取消成功！',
                icon: 'none',
                duration: 1500
              });
              this._refreshData();
            }
          })
        }
      }
    })
  },
  OpenPop(e) {
    var order = e.currentTarget.dataset.order;
    this.setData({
      showPop: true,
      curOrder: order
    });
  },
  toAudit(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/packageAudit/do-audit/do-audit?id=" + id
    })
  },
  toPeople(e){
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/packageAudit/assist-people/assist-people?id=" + id
    })
  },
  leave() {
    this.setData({
      curOrder: null
    });
  }
})